/*封装请求*/
import axios from 'axios';
import store from '@/store';
import { Toast } from 'vant';
import {getToken, getRefreshToken} from '@/utils/cache';
import {str2Base64} from "../utils/utils";

// const baseUrl = '/api/' //测试
const baseUrl = 'http://yfgpwebapi.fszyrj.com/schoolBus/' //正式


//创建实例
const request = axios.create({
  timeout: 60000,
  // baseURL: process.env.VUE_APP_URL
  baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_URL : window.webConfig.webApiBaseUrl
});

//请求拦截
request.interceptors.request.use(
  config => {
    //发送请求前
    config.headers['Authorization'] = `Bearer ${getToken()}`
    return config
  },
  error =>{
    //请求出错
    return Promise.reject(error)
  }
);

//响应拦截
request.interceptors.response.use(
  async res => {
    const status = res.status;
    let data = res.data;
    //未授权
    if (status === 401 || data.errcode === 401){
      await refreshToken();
      exprReqNum--

      //重新请求
      data = await reRequest(res.config);

    }
    if (!data.root) return data;
    let root = data.root,
      {errcode,errmsg} = root.response || {},
      {row} = root.data || {},
      totalsize = root.page && root.page.totalsize || 0;
    console.log(root);
    if (errcode !== 0){
      Toast(errmsg);
    }
    return {total: totalsize,row,errmsg,errcode}
  },
  error => {
    console.log('请求出错',error);
  }
);

let refreshPromise = null,
  // token过期请求数量
  exprReqNum = 0;
function refreshToken() {
  let post = {
    refresh_token: getRefreshToken(),
  }
  if (!refreshPromise || !exprReqNum){
    refreshPromise = new Promise((resolve )=>{
      if (post.refresh_token){
        exprReqNum = 0;
        //重新登录操作....
        return
      }
      //调用刷新token接口
      setTimeout(res => {
        //刷新成功
        if (res){
          store.dispatch('login',res);
          resolve();
        }
        //失败，重新登录...
        // let uri = process.env.VUE_APP_DOMAIN + '/SchoolBusWechat/index.html',
        let domain = process.env.VUE_APP_DOMAIN,
          dir = process.env.VUE_APP_SECONDDIR;
        if (process.env.NODE_ENV !== 'development') {
          domain = window.webConfig.webApiBaseDomain;
          dir = window.webConfig.webSecondDir
        }
        let uri = domain + dir + 'index.html',
          url = str2Base64(uri)
        // location.replace( process.env.VUE_APP_PATH + '/api/v1/LoginWeChat/Index2?url=' + url)
        // 250416 yan 注销
        // location.replace( (process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath) + '/api/v1/LoginWeChat/Index2?url=' + url)
      },300)
    })
  }
  exprReqNum++
  return refreshPromise
}

// 重新请求函数
function reRequest(config) {
  return new Promise((resolve) =>{
    request(config).then(() => {
      resolve()
    })
  })


}


/**
 * get请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const get = (url,data)=>{
  return new Promise((resolve,reject ) => {
    if (data) {
      let keys = Object.keys(data);
      let arr = keys.map(item => item + '=' + data[item]);
      url = url + '?' + arr.join('&')
    }
    request.get(url).then(res => {
      resolve(res)
    }, err => {
      reject();
    })
  })
}
/**
 * post 请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const post = (url,data,config)=>{
  return new Promise((resolve,reject ) => {
    request.post(url, data,config).then(res => {
      console.log(res);
      resolve(res);
    }, err => {
      reject();
    })
  })
}
/**
 * put请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const put = (url,data)=>{
  return new Promise((resolve,reject ) => {
    request.put(url, data).then(res => {
      resolve(res)
    }, err => {
      reject();
    })
  })
}
/**
 * patch请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const patch = (url,data)=>{
  return new Promise((resolve,reject ) => {
    request.patch(url, data).then(res => {
      resolve(res)
    }, err => {
    })
  })
}

/**
 * 删除请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const del = (url,data)=>{
  return new Promise((resolve,reject ) => {
    /*if (data) {
      let keys = Object.keys(data);
      let arr = keys.map(item => item + '=' + data[item]);
      url = url + '?' + arr.join('&')
    }*/
    request.delete(url,{data}).then(res => {
      resolve(res)
    }, err => {
    })
  })
}

export default request;

